<?php
require_once '../vendor/autoload.php';

use Workerman\Worker;
use Workerman\Lib\Timer;
use PHPSocketIO\SocketIO;

require_once './SingleMysql.php';
require_once './SingleRedis.php';

$web_socketio = new SocketIO(12121);
$mysql = SingleMysql::getInstance();
//$redis = SingleRedis::getInstance();
$config = require './config.php';
$redis = new Redis();
$redis->connect($config['redis']['db_host'], $config['redis']['db_port']);
//为了让超时的服务永不超时？有用吗
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
//开始
$web_socketio->on('workerStart', function () use ($web_socketio) {
    //重新打开一个http接口 负责tp5来触发io事件
    $inner_http_worker = new Worker('http://0.0.0.0:12131');
    $inner_http_worker->onMessage = function ($http_connection, $data) use ($web_socketio) {
        if (!isset($_POST['data'])) {
            return $http_connection->send('fail, msg not found');
        }
        $data = json_decode($_POST['data'], true);
        $type = $data['type'];
        /**
         *  type的类型
         *  transferEnd : 转写结束
         */
        switch ($type) {
            case 'transferEnd':
                $respones_data = [
                    'meeting_id' => $data['mid']
                ];
                $web_socketio->emit('transfer over', $respones_data);
                break;
            default:
                break;
        }
        $http_connection->send('ok');
    };
    $inner_http_worker->listen();
    //设置非阻塞判断
    $lock = 1;
    //定时从队列中获取转写数据
    Timer::add(0.2, function()use($web_socketio,&$lock){
        global $redis;
        if(!$lock)
        {
            return;
        }
        if($redis){
            $lock = 0;
            //循环读取数据
            while(1)
            {
                $mq_pop = $redis->rPop('transferMQ');
                if(!$mq_pop)
                {
                    $lock = 1;
                    return;
                }
                $data = json_decode($mq_pop,true);
                if(!$data)
                {
                    continue;
                }
                $web_socketio->to($data['mid'])->emit('get audio info', $data['transfer']);
            }
            $lock = 1;
        }
    });
});

//事件
$web_socketio->on('connection', function ($socket) use ($web_socketio) {
    //登录功能 上传token userid meetingid
    $socket->on("get audio history", function ($msg) use ($socket) {
        global $redis, $mysql;
        //判断$msg是否为json
        $msg_data = json_decode($msg, true);
        if (!$msg_data) {
            echo "格式不准确";
            return;
        }
        //获取$msg_data中的用户验证信息
        $auth_key = $msg_data['token'];

        //meetingid设置
        $mid = $msg_data['meeting_id'];
        //获取当前录音转写状态
        $lid = $mysql->select('end_time')->from('rszh_meeting_live_speech')->where('meeting_tag = :mid')->bindValues(['mid' => $mid])->query();
        //接收历史记录
        //historical($mid);
        {
            //初始化发送的历史记录接送、字符串
            $dispatch = [];
            $br = [
                'or_txt' => '<br>',
                'ed_txt' => '',
                'url' => '',
                'paly_time' => 0,
                'status' => 1,
                'timestamp' => '',
                'sc' => 0
            ];
            $dispatch[] = json_encode($br);
            //获取结果hash中的结果
            //hVals转换结果乱序
            //$dispatch = $redis->hVals($mid);
            $count = $redis->hget($mid . '_state', 'lower') - 1;
            for ($i = 1; $i <= $count; $i++) {
                $result = $redis->hget($mid, $i);
                $result_la = $redis->hget($mid, $i - 1);
                $result_arr = json_decode($result, true);
                $result_la_arr = json_decode($result_la, true);

                if ($result_arr['sc'] != $result_la_arr['sc']) {
                    $br = [
                        'or_txt' => '<br>',
                        'ed_txt' => '',
                        'url' => '',
                        'paly_time' => 0,
                        'status' => 1,
                        'timestamp' => '',
                        'sc' => $result_la_arr['sc'] ? $result_la_arr['sc'] : 0

                        //'sorting' => $sorting + 0,
                    ];
                    $dispatch[] = json_encode($br);
                }
                $dispatch[] = $redis->hget($mid, $i);
            }
            //返回给连接用户的值
            $data = [
                'list' => $dispatch,
                'total' => count($dispatch)
            ];
        }
        $socket->emit('get audio history', $data);
        //$socket->broadcast->emit('get audio history', $data);
    });

    //web加入meetingid的组，并实时获取在线转写的消息
    $socket->on('get audio info', function ($msg) use ($socket) {
        //判断$msg是否为json
        $msg_data = json_decode($msg, true);
        if (!$msg_data) {
            echo "格式不准确";
            return;
        }
        //获取$msg_data中的用户验证信息
        $auth_key = $msg_data['token'];

        //meetingid设置
        $mid = $msg_data['meeting_id'];
        //加入群组
        $socket->emit('prompt message', "加入" . $mid . "组");
        $socket->join($mid);
    });

    $socket->on('edit', function ($msg) use ($socket) {
        try {
            global $mysql, $redis;
            //echo $msg . "\n";
            $msg = json_decode($msg, true);
            if (!$msg) {
                $socket->emit('edit', "msg格式不正确");
                return;
            }
            //获取$msg_data中的用户验证信息
            $auth_key = $msg['token'];
            //获取$msg_data中的edit的数组
            $changed =  json_decode($msg['data'], true);
            if (!$changed) {
                $socket->emit('edit', "data格式不正确");
                return;
            }
            if ($changed['or_txt'] == "<br>") {
                return;
            }
            //获取meeting_id
            $mid = $msg['meeting_id'];
            //获取meeting对应表的lid
            $lid = $redis->hGet('meeting_to_lid', $mid);
            //判断meeting是否储存在对应表id的hash中
            if (!$lid) {
                //如果不存在则
                $socket->emit('edit', "未找到修改文件");
                return;
            }
            //查找哈希 中的数据
            $origin = $redis->hGet($mid, $changed['sorting']);
            if (empty($origin)) {
                $socket->emit('edit', "未找到原始数据");
                return;
            }
            $transfer = json_decode($origin, true);
            if (!$transfer['status']) {
                $socket->emit('edit', "文字状态为未完成，禁止修改");
                return;
            }
            $transfer['ed_txt'] = $changed['ed_txt'];
            if ($transfer['ed_txt'] === "") {
                $transfer['ed_txt'] = " ";
            }
            $edit_data = json_encode($transfer, JSON_UNESCAPED_UNICODE);
            //插入hash和数据库
            $redis->hSet($mid, $changed['sorting'], $edit_data);
            $save = [
                "lid" => $lid,
                //"transfer" => $transfer['or_txt'],
                "editor" => $transfer['ed_txt'],
                //"url" => $transfer['url'],
                //"pcmtime" => $transfer['paly_time'] . '',
                //"sorting" => $transfer['sorting'],
                "update_time" => time()
            ];
            $res = $mysql->update('rszh_meeting_convert')->cols($save)->where("lid = " . $lid . " AND sorting = " . $transfer['sorting'])->query();
            //为rszh_meeting_live_speech的对应数据更新编辑状态
            if (!$redis->hGet($mid . "_state", 'editstate')) {
                $res = $mysql->update('rszh_meeting_live_speech')->cols(['edit_state' => 1])->where("meeting_tag = :mid")->bindValue('mid', $mid)->query();
                $redis->hSet($mid . "_state", 'editstate', 1);
            }
            $redis->lPush('editMQ', json_encode(['mid' => $mid, 'editor' => $edit_data], JSON_UNESCAPED_UNICODE));
            // //盒子端同屏修改
            // $res2 = $mysql->select("did,end_time")->from('rszh_meeting_live_speech')->where('meeting_tag= :mid')->bindValues(array('mid' => $mid))->row();
            // //获取盒子端的socket
            // $box_socket = $box_sockets[$res2['did']];
            // if (!empty($box_socket)) {
            //     //获取全部信息
            //     $all_message = '';
            //     $count = $redis->hget($mid . '_state', 'lower') - 1;
            //     for ($i = 1; $i <= $count; $i++) {
            //         $datas = json_decode($redis->hget($mid, $i), true);
            //         $next_datas = json_decode($redis->hget($mid, $i + 1), true);
            //         if ($datas['sc'] != $next_datas['sc']) {
            //             $all_message .= $datas['ed_txt'] ? trim($datas['ed_txt']) . "\n\t" : trim($datas['or_txt']) . "\n\t";
            //             continue;
            //         }
            //         $all_message .= $datas['ed_txt'] ? trim($datas['ed_txt']) : trim($datas['or_txt']);
            //     }
            //     $all_message = substr($all_message, 0, strrpos($all_message, "\n"));
            //     $all_message = "\t" . $all_message;
            //     echo $all_message;
            //     $box_socket->emit('boxedit', $all_message);
            // }
            // if (!empty($box_socket) && empty($res2['endtime'])) {
            //     //获取全部信息
            //     $all_message = '';
            //     $count = $redis->hget($mid . '_state', 'lower') - 1;
            //     for ($i = $count; $i >= 1; $i--) {
            //         if (strlen($all_message) >= 600) {
            //             break;
            //         }
            //         $datas = json_decode($redis->hget($mid, $i), true);
            //         $str = $datas['ed_txt'] ? trim($datas['ed_txt']) : trim($datas['or_txt']);
            //         if (strlen($str . $all_message) >= 2048) {
            //             break;
            //         }
            //         $last_datas = json_decode($redis->hget($mid, $i - 1), true);
            //         if ($datas['sc'] != $last_datas['sc']) {
            //             $all_message = ("\n\t" . $str) . $all_message;
            //             continue;
            //         }
            //         $all_message = $str . $all_message;
            //     }
            //     if ($n_pos = strpos($all_message, "\n") === 0) {
            //         $all_message = substr($all_message, $n_pos);
            //     }
            //     //$all_message = substr($all_message, 2);
            //     echo $all_message;
            //     $box_socket->emit('boxedit', $all_message);
            // }
            //返回
            if ($res) {
                $data = [
                    "code" => 200,
                    "message" => "修改成功"
                ];
                $socket->emit('edit', $data);
            }
        } catch (\Exception $e) {
            $data = [
                "code" => 400,
                "message" => $e->getMessage()
            ];
            $socket->emit('edit', $data);
            echo $e->getMessage();
        }
    });
});

header("ALLOW-CONTROL-ALLOW-ORIGIN:*");
// 如果不是在根目录启动，则运行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}
